/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 *
 * https://www.renren.io
 *
 * 版权所有，侵权必究！
 */

package com.guoj.easyweb.config;

import com.guoj.easyweb.interceptor.AuthorizationInterceptor;
import com.guoj.easyweb.interceptor.HttpInterceptor;
import com.guoj.easyweb.interceptor.LoginInterceptor;
import com.guoj.easyweb.resolver.LoginUserHandlerMethodArgumentResolver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

/**
 * MVC配置
 *
 * @author Mark sunlightcs@gmail.com
 */
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

	@Autowired
	private LoginInterceptor loginInterceptor;

	@Autowired
	private HttpInterceptor httpInterceptor;

	@Autowired
	private AuthorizationInterceptor authorizationInterceptor;

    @Autowired
    private LoginUserHandlerMethodArgumentResolver loginUserHandlerMethodArgumentResolver;

	/**
	 * 注册拦截器
	 * 	-- springboot1.5.x，会自己识别static、public、resources下静态资源，不会被拦截。
	 * 	-- springboot2.x之后，如果拦截/**所有请求，那么静态资源也会被拦截器拦截，需要自己排除。
	 * @param registry
	 */
	@Override
    public void addInterceptors(InterceptorRegistry registry) {
		registry.addInterceptor(authorizationInterceptor).addPathPatterns("/app/**") // 拦截app访问
													.excludePathPatterns("/app/login"); // 排除登录接口

		registry.addInterceptor(httpInterceptor).addPathPatterns("/**");// 拦截所有http请求

		registry.addInterceptor(loginInterceptor).addPathPatterns("/user/**", "/spa/**.html")
													.excludePathPatterns("/spa/login.html") // 排除登录拦截
													.excludePathPatterns("/swagger-resources") // 排除swagger拦截
													.excludePathPatterns("/v2/**"); // 排除swagger拦截

//        registry.addInterceptor(authorizationInterceptor).addPathPatterns("/**")
//				.excludePathPatterns("/spa/login.html", "/user/login", "/getVerify") // 不拦截的url
//				.excludePathPatterns("/spa/assets/**", "/spa/json/**", "/spa/lay/**", "/swagger/**") // 排除静态资源和swagger
//				.excludePathPatterns("/error"); // 排除错误请求的拦截
    }

    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
        argumentResolvers.add(loginUserHandlerMethodArgumentResolver);
    }
}